

from flask import request
from utils.randomUtils import  generate_random_by_time
import threading
from .baseGraphNode import  *
from ..execute.baseExeHis import BaseExeHis
from .sessionInfo import SessionInfo

class HttpOutGraphNode(BaseGraphNode):
    
    socketio_instances = {}
    def __init__(self, id:str, data:dict, graphNodeManager, random_key:str):
        super().__init__(id, data, graphNodeManager, random_key)
        self.route = data['data']['route']
        self.role = data['data'].get('role', 'assistant')
        self.running = False

    def execute(self, session_info: SessionInfo=None, exe_his: BaseExeHis=None, **kwargs):
        assert session_info is not None, "session_info should not be None when return message"
        # return-msg
        returnMsg = ''
        if 'return-msg' in self.dict['in']: # {'nodeId': sourceID, 'handle': sourceHandle}
            msgFrom = self.dict['in']['return-msg']
            prenode =self.graphNodeManager.nodesByIdDict[msgFrom['nodeId']]
            returnMsg = prenode.get_newest_output_in_session(session_info, msgFrom['handle'])
        # for nodek,nodev in session_info.out.items():
        #     for handlek,handlev in nodev.items():
        #         p = ""
        #         for it in handlev:
        #             try:
        #                 p+="-------\n"+it.content+"\n------"
        #             except:
        #                 pass
        #         print(f"{nodek}, with {handlek} has {p}")
        exe_his.update_content("outputed")
        exe_his.done()
        session_info.ws.emit(self.route, {'data': returnMsg.content, 'role': self.role}, room=session_info.id, namespace=session_info.full_url)
        return session_info.full_url
    
